//
//  ClockListView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/16.
//

import SwiftUI
import UTEBluetoothRYApi
import ToastUI

struct ClockListView: View {
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel = DeviceDetailVM()
    @State private var alarms = UTEModelClock()
    @State private var showToast = false

    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName:"addDevice", title: "日常闹钟") {
                if viewModel.alarmArray.count == 5{
                    showToast = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        showToast = false
                    }
                    return
                }
                let alarm : UTEModelClock = UTEModelClock()
                alarm.index = findMissingMinIndex()
                appState.navigateTo(.clocksetting(id: alarm,isEdit: false))
            }
            List {
                ForEach($viewModel.alarmArray, id: \.index) { $alarm in
                    Button(action: {
                        appState.navigateTo(.clocksetting(id: alarm,isEdit: true))
                    }) {
                        ClockView(item: $alarm)
                    }
                    .frame(height: 83)
                    .background(Color(hex: "#1E1E1E"))
                    .cornerRadius(16)
                    .padding(.horizontal,12)
                    .padding(.top,12)
                    .listRowSeparator(.hidden)
                    .listRowInsets(EdgeInsets())
                    .listRowBackground(Color.clear)
                    .swipeActions(edge: .trailing) {
                        Button(role: .destructive) {
                            // 删除操作
                            viewModel.delecteAlarmArrayModel(alarm: alarm) { success in
                                if success {
                                    viewModel.getAlarmArray()
                                }
                            }
                        } label: {
                            Label("删除", systemImage: "trash")
                        }
                    }
                }
            }
            .listStyle(.plain)
            .environment(\.defaultMinListHeaderHeight, 0.1)
            .scrollIndicators(.hidden)
            .listRowInsets(EdgeInsets())
            
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .onAppear {
            viewModel.getAlarmArray()
        }
        .toast(isPresented: $showToast) {
            ShowMessageView(message: "最多支持5个闹钟")
        }
    }
    
    //计算闹钟的index
    func findMissingMinIndex(maxIndex: Int = 5) -> Int {
        let existingIndices = Set(viewModel.alarmArray.map { $0.index })
        for i in 1...maxIndex {
            if !existingIndices.contains(i) {
                return i
            }
        }
        return maxIndex + 1
    }
    
    
}

#Preview {
    ClockListView()
}
struct ClockView: View {
    @StateObject var viewModel = DeviceDetailVM()
    @Binding var item : UTEModelClock
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                Text(String(format: "%02d:%02d", item.timeHour,item.timeMin))
                    .font(.system(size: 30))
                    .foregroundStyle(Color(hex: "#B1B1B1"))
                let a :Int = Int(item.cycle)
                let date:[String] = UTEWeekType.getWeekdayNames(from: a)
                Text(date.joined(separator: " "))
                    .foregroundStyle(Color(hex: "#B1B1B1"))
            }
            .padding(.leading,16)
            Spacer()
            Toggle("", isOn: $item.enable)
                .toggleStyle(SwitchToggleStyle(tint: Color(hex: "#00E9DA")))
                .frame(width: 47,height: 27)
                .padding(.trailing,16)
        }
        .onChange(of: item.enable) {newValue in
            viewModel.setAlarmArrayModel(alarms: [item]) { success, dic in
                if success {
                    print("设置成功")
                }else {
                    print("设置失败")
                }
            }
        }
    }
}
